package com.xcc.httpUtils.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Carman
 * <p>
 * Date: 2017/11/3 - 18:03
 * <p>
 * 描述: 格式化 url 请求参数。
 * 通过 url + map 集合，格式化为一个可用的 get 请求链接
 */
public class FormatUrlParams {

    private final static String ONE_ATTACH = "?";
    private final static String ATTACH = "&";

    public static String formatUrl(String url, Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append(url);
        int len = keys.size();
        String tempKey = "";
        for (int i = 0; i < len; i++) {
            tempKey = keys.get(i);
            sBuilder.append(getAttach(i) + tempKey + "=" + params.get(tempKey));
        }
        return sBuilder.toString();
    }

    /**
     * 获取连接符号
     *
     * @param index
     * @return
     */
    private static String getAttach(int index){
       return index == 0? ONE_ATTACH:ATTACH;
    }
}
